package com.yaj.myfactorysupport.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName WebSocketHandler
 * @Description WebSocket处理类
 * @date 2022/1/9 7:21
 * @Version 1.0
 */
@ServerEndpoint("/websocket/{token}")
@Component
@Slf4j
public class WebSocketHandler {
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    @OnOpen
    public void openHandler(Session session, @PathParam("token") String token){
        if(token == null || "".equals(token)){
            this.sendMessage(session,"【Error】客户端Token错误，连接失败");
        }
        sessionPools.put(token,session);

        this.sendMessage(session,"连接成功");
    }

    @OnClose
    public void closeHandler(@PathParam("token") String token){
        if(sessionPools.containsKey(token)){
            sessionPools.remove(token);
        }
    }

    @OnMessage //收到客户端发来的消息
    public void messageHandler(Session session, String message){

    }

    /**
     * 群发消息
     * @param message
     */
    public void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : sessionPools.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }

    private void sendMessage(Session session, String message) {
        //判断当前session是否存在
        if(session != null){
            synchronized (session){ //做一个同步
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
}
